package cn.gx.kevin.config;

import cn.gx.kevin.common.bootenv.SpringContextUtil;
import cn.gx.kevin.common.ui.DataGrid;
import cn.gx.kevin.common.ui.DataGridHelper;
import cn.gx.kevin.common.utils.ISpringContextListener;
import cn.gx.kevin.common.utils.SysConfigParams;
import cn.gx.kevin.domain.Dict;
import cn.gx.kevin.domain.Func;
import cn.gx.kevin.domain.Menu;
import cn.gx.kevin.domain.User;
import cn.gx.kevin.service.IDictService;
import cn.gx.kevin.service.IFuncService;
import cn.gx.kevin.service.IMenuService;
import cn.gx.kevin.service.IUserService;
import com.alibaba.fastjson.JSONObject;
import com.github.yitter.contract.IdGeneratorOptions;
import com.github.yitter.idgen.YitIdHelper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.*;


@Service("springContextListener")
public class OnSpringEnvStarted implements ISpringContextListener {

    private static final Logger logger = LoggerFactory.getLogger(OnSpringEnvStarted.class);

    @Autowired
    IDictService dictService;

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private Environment environment;

    @Override
    public void onEnvFinished() {
        String serverAddress = "";
        try{
            serverAddress = InetAddress.getLocalHost().getHostAddress();
        }catch (Exception x){
            logger.error("",x);
        }
        logger.info("onEnvFinished ,go to set IdGenerator workid,serverAddress:{} ,serverPort:{} ",serverAddress,serverPort);
        String key = serverAddress+":"+serverPort;
        short workId = 1;
        String typeid  = "dbWorkId";
        Map<String,Object> params = new HashMap<>();
        params.put("typeid",typeid);
        Dict newDict = null;
        try{
           List<Dict> dicts = dictService.selectParam(params);
           if(dicts.size() == 0){
               newDict = new Dict();
               newDict.setDvalue(String.valueOf(workId));
           }else {
               short maxId = 0;
               boolean isFind = false;
               for(Dict dict : dicts){
                   if(key.equals( dict.getDkey())){
                       isFind = true;
                       workId = Short.valueOf( dict.getDvalue());
                       break;
                   }
                   short tmpId = Short.valueOf( dict.getDvalue());
                   if(tmpId > maxId){
                       maxId = tmpId;
                   }
               }
               if(!isFind){
                   newDict = new Dict();
                   newDict.setDvalue(String.valueOf(maxId+1));
               }
           }
        }catch (Exception x){
            logger.error("Init DB WORKID IS EROOR :{}",x);
        }
        //YitIdHelper 设置workid
        IdGeneratorOptions options = new IdGeneratorOptions(workId);
        YitIdHelper.setIdGenerator(options);
        if(newDict != null){
            newDict.setTypeid(typeid);
            newDict.setDesp("data center id");
            newDict.setDkey(key);
            newDict.setReadonly(1);
            try{
                dictService.insert(newDict);
            }catch (Exception x){
                logger.error("Insert DB WORKID IS EROOR :{}",x);
            }
        }
        //读取datagrid配置形成权限配置数据
        initSysFunc();
    }

    @Override
    public void onBeforeEvnDestory() {

    }



    private void initSysFunc(){
        // 读取所有的datagrid配置的url/按钮数据形成func功能表的数据
        if (SysConfigParams.isDevModel()) {
            logger.info("初始化系统功能表..................................................");
            try {
                IMenuService menuService = (IMenuService) SpringContextUtil.getBean("menuService");
                IFuncService funcService = (IFuncService) SpringContextUtil.getBean("funcService");
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("controller", 1);
                Map<String, Menu> menuMap = menuService.selectMap(param, "controller");

                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                //factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                PathMatchingResourcePatternResolver resoler = new PathMatchingResourcePatternResolver();
                String datagridCfg = "classpath*:/datagrid/**/*-datagrid.xml";
                logger.info("Start <<<<< 读取datagrid配置，将配置的功能写入func表  >>>>>>>");
                Resource[] dataGridResource = resoler.getResources(datagridCfg);
                for (Resource r : dataGridResource) {
                    InputStream xmlinput = r.getInputStream();
                    Document docgrid = builder.parse(xmlinput);
                    DataGrid grid = DataGridHelper.readGridFromXml(docgrid, null);
                    String url = grid.getUrl().replace("/list", "");
                    Menu menu = menuMap.get(url);
                    if (menu != null) {
                        Map<String, String> cmdArr = grid.getAllCmdDesp();
                        Set<Map.Entry<String, String>> entrySet = cmdArr.entrySet();
                        List<Func> listFunc = new ArrayList<Func>();
                        for (Map.Entry<String, String> es : entrySet) {
                            Func f = new Func();
                            f.setCreateTime(new Date());
                            String cmd = es.getValue();
                            f.setIsLog("0");
                            f.setFuncDesc(es.getKey());
                            f.setFuncCode(cmd);
                            f.setMenuId(menu.getId());
                            listFunc.add(f);
                        }
                        Func queryf = new Func();
                        queryf.setCreateTime(new Date());
                        queryf.setIsLog("0");
                        queryf.setFuncDesc("查询");
                        queryf.setFuncCode("list");
                        queryf.setMenuId(menu.getId());
                        listFunc.add(queryf);
                        funcService.insertList(listFunc);
                    }
                }

                IUserService userService = (IUserService)SpringContextUtil.getBean("userService");
                User superAdmin = userService.get("0");
                if (superAdmin == null) {
                    logger.info("<<<<< 初始化系统超级用户 >>>>>> ");
                    String pwd = DigestUtils.md5Hex("Admin@nn90");
                    String name = "admin";
                    String adminName = "超级管理员";
                    userService.insertSuperAdmin(name, adminName, pwd);
                }
                logger.info("初始化系统功能表,完成！..................................................");
            } catch (Exception ex) {
                logger.error("",ex);
            }
        }
    }
}
